﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Windows.Forms;
using System.Data;
using QASampling.BusinessObject;
using QASampling.Util;
using System.Drawing;
using System.Globalization;

namespace QASampling.QAControl
{
    class QADataGrid : QABaseDataGrid
    {
        private ToolTip[] tooltip;
        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }

        private string tableSource;
        public string TableSource
        {
            get { return tableSource; }
            set 
            { 
                tableSource = value;
                NotifyPropertyChanged("TableSource");
            }
        }

        private string[] fieldName;
        public string[] FieldName
        {
            get { return fieldName; }
            set { fieldName = value; }
        }

        private string[] labelText;
        public string[] LabelText
        {
            get { return labelText; }
            set { labelText = value; }
        }

        private string fieldRules = string.Empty;
        public string FieldRules
        {
            get { return fieldRules; }
            set { fieldRules = value; }
        }

        private string[] dateFormat;
        public string[] DateFormat
        {
            get { return dateFormat; }
            set { dateFormat = value; }
        }

        private JenisField[] fieldType;
        public JenisField[] FieldType
        {
            get { return fieldType; }
            set { fieldType = value; }
        }

        private int[] digits;
        public int[] Digits
        {
            get { return digits; }
            set { digits = value; }
        }

        private string[] errorMsg;
        public string[] ErrorMsg
        {
            get { return errorMsg; }
            set { errorMsg = value; }
        }

        private JenisDB dbType = JenisDB.Datacap;
        public JenisDB DBType
        {
            get { return dbType; }
            set { dbType = value; }
        }

        private string tableNo = string.Empty;
        public string TableNo
        {
            get { return tableNo; }
            set { tableNo = value; }
        }

        public QADataGrid()
        {
            InitializeComponent();
            this.PropertyChanged += OnPropertyChanged;
        }

        void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            try
            {                 
                if (e.PropertyName == "TableSource")
                {
                    if (!string.IsNullOrEmpty(tableSource))
                    {
                        if (fieldName.Length != labelText.Length)
                            return;
                        this.Columns.Clear();
                        for (int i = 0; i < fieldName.Length; i++)
                        {
                            DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();
                            column.Name = fieldName[i];
                            column.DataPropertyName = fieldName[i];
                            column.HeaderText = labelText[i];                            
                            column.SortMode = DataGridViewColumnSortMode.Automatic;
                            if (fieldType[i] == JenisField.Datetime)
                                column.DefaultCellStyle.Format = dateFormat[i];
                            if (fieldType[i] == JenisField.Currency)
                            {
                                string numericFormat = "N" + digits[i];
                                column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                                column.DefaultCellStyle.Format = numericFormat;
                                column.DefaultCellStyle.FormatProvider = CultureInfo.GetCultureInfo("id-ID");
                            }
                            this.Columns.Add(column);

                            if (fieldName[i].Equals("DOCID") || fieldName[i].Equals(QAConstants.MUST_HAVE_FIELD))
                            {
                                column.Visible = false;                              
                            }                            
                        }
                        if (dbType.Equals(JenisDB.Datacap))
                        {
                            if (!string.IsNullOrEmpty(tableNo))
                            {
                                this.DataSource = QAController.GetSPTWithFieldFor1108(tableSource, fieldName, tableNo);
                            } 
                            else
                                this.DataSource = QAController.GetSPTWithFieldForGrid(tableSource, fieldName);
                        }
                        else
                            this.DataSource = QAController.GetQAChangeLog(tableSource, fieldName);
                        if (this.Columns.Contains(QAConstants.MUST_HAVE_FIELD))
                            this.Sort(this.Columns[QAConstants.MUST_HAVE_FIELD], ListSortDirection.Ascending);

                        this.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
                        this.Refresh();
                        this.errorMsg = new string[this.RowCount];
                        this.tooltip = new ToolTip[this.RowCount];
                        for (int i = 0; i < this.RowCount; i++)
                        {
                            tooltip[i] = new ToolTip();
                            tooltip[i].AutoPopDelay = 1000;
                            tooltip[i].InitialDelay = 1000;
                            tooltip[i].ReshowDelay = 500;
                            try
                            {
                                this.errorMsg[i] = string.Empty;
                                if (this.FindForm() != null)
                                {
                                    if (!ValidationUtil.CalculateGrid(this.Rows[i], this.fieldRules, this.labelText, ref errorMsg[i]))
                                    {
                                        SetBackgroundColor(i);
                                        QAFieldErrorMsg fem = new QAFieldErrorMsg();
                                        //fem.DocId = QAController.DocId;                        
                                        //fem.Field = this.LabelText;
                                        fem.ErrorMsg = errorMsg[i];
                                        if (QAController.FieldErrorMsg.IndexOf(fem) < 0)
                                            QAController.FieldErrorMsg.Add(fem);
                                        tooltip[i].Show(string.Empty, this, 0);
                                        /*temp
                                        tooltip[i].SetToolTip(this, errorMsg[e.RowIndex]);
                                        tooltip[e.RowIndex].Show(errorMsg[e.RowIndex], this, Width - 40, Height, 2000);
                                         */
                                    }
                                    else
                                    {
                                        /*temp
                                        errorMsg[e.RowIndex] = string.Empty;
                                        SetBackgroundColor(e.RowIndex);
                                        */

                                        /*if (fieldType.Equals(JenisField.Datetime))
                                        {
                                            if (!String.IsNullOrEmpty(Text) && !ValidationUtil.IsValidDate(Text, dateFormat))
                                            {
                                                BackColor = Color.Red;
                                                errorMsg += " Masukkan penanggalan dengan benar " + dateFormat;
                                                QAFieldErrorMsg fem = new QAFieldErrorMsg();
                                                //fem.DocId = QAController.DocId;
                                                fem.Field = this.LabelText;
                                                fem.ErrorMsg = errorMsg;
                                                tooltip.Show(string.Empty, this, 0);
                                                tooltip.SetToolTip(this, errorMsg);
                                                tooltip.Show(errorMsg, this, Width - 40, Height, 2000);
                                            }
                                        }
                                        else if (fieldType.Equals(JenisField.Currency))
                                        {
                                            if (!ValidationUtil.IsValidCurrency(Text, true))
                                            {
                                                BackColor = Color.Red;
                                                errorMsg += " Masukkan penulisan uang dengan benar";
                                                QAFieldErrorMsg fem = new QAFieldErrorMsg();
                                                //fem.DocId = QAController.DocId;
                                                fem.Field = this.LabelText;
                                                fem.ErrorMsg = errorMsg;
                                                tooltip.Show(string.Empty, this, 0);
                                                tooltip.SetToolTip(this, errorMsg);
                                                tooltip.Show(errorMsg, this, Width - 40, Height, 2000);
                                            }
                                        }*/
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                // throw ex;
                            }

                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return;
            }
        }

        private void InitializeComponent()
        {
            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
            ((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
            this.SuspendLayout();
            // 
            // QADataGrid
            // 
            this.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
            dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
            dataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.Control;
            dataGridViewCellStyle1.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.WindowText;
            dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.Highlight;
            dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
            dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
            this.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle1;
            this.TabStop = false;
            this.ColumnAdded += new System.Windows.Forms.DataGridViewColumnEventHandler(this.QADataGrid_ColumnAdded);
            this.RowValidating += new System.Windows.Forms.DataGridViewCellCancelEventHandler(this.QADataGrid_RowValidating);
            this.Validating += new System.ComponentModel.CancelEventHandler(this.QADataGrid_Validating);
            ((System.ComponentModel.ISupportInitialize)(this)).EndInit();
            this.ResumeLayout(false);

        }

        private void QADataGrid_ColumnAdded(object sender, DataGridViewColumnEventArgs e)
        {
            this.ClearSelection();

            //--added by Vincent 20130114 for row number--
            //dgvJob.RowHeadersWidthSizeMode = System.Windows.Forms.DataGridViewRowHeadersWidthSizeMode.AutoSizeToDisplayedHeaders; 
           /* int rowNumber = 1;
            foreach (DataGridViewRow row in this.Rows)
            {
                if (row.IsNewRow) continue;
                row.HeaderCell.Value = "" + rowNumber;
                rowNumber = rowNumber + 1;
            }
            this.RowHeadersWidth = 50;*/
            //dgvJob.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders);  
        }

        private void QADataGrid_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {
            try
            {
                this.errorMsg[e.RowIndex] = string.Empty;
                if (this.FindForm() != null)
                {
                    if (!ValidationUtil.CalculateGrid(this.Rows[e.RowIndex], this.fieldRules, this.labelText, ref errorMsg[e.RowIndex]))
                    {
                        SetBackgroundColor(e.RowIndex);
                        e.Cancel = false;
                        QAFieldErrorMsg fem = new QAFieldErrorMsg();
                        //fem.DocId = QAController.DocId;                        
                        //fem.Field = this.LabelText;
                        fem.ErrorMsg = errorMsg[e.RowIndex];
                        if (QAController.FieldErrorMsg.IndexOf(fem) < 0)
                            QAController.FieldErrorMsg.Add(fem);
                        tooltip[e.RowIndex].Show(string.Empty, this, 0);
                        tooltip[e.RowIndex].SetToolTip(this, errorMsg[e.RowIndex]);
                        tooltip[e.RowIndex].Show(errorMsg[e.RowIndex], this, Width - 40, Height, 2000);                        
                    }
                    else
                    {
                        e.Cancel = false;
                        errorMsg[e.RowIndex] = string.Empty;
                        SetBackgroundColor(e.RowIndex);

                        /*if (fieldType.Equals(JenisField.Datetime))
                        {
                            if (!String.IsNullOrEmpty(Text) && !ValidationUtil.IsValidDate(Text, dateFormat))
                            {
                                BackColor = Color.Red;
                                errorMsg += " Masukkan penanggalan dengan benar " + dateFormat;
                                QAFieldErrorMsg fem = new QAFieldErrorMsg();
                                //fem.DocId = QAController.DocId;
                                fem.Field = this.LabelText;
                                fem.ErrorMsg = errorMsg;
                                tooltip.Show(string.Empty, this, 0);
                                tooltip.SetToolTip(this, errorMsg);
                                tooltip.Show(errorMsg, this, Width - 40, Height, 2000);
                            }
                        }
                        else if (fieldType.Equals(JenisField.Currency))
                        {
                            if (!ValidationUtil.IsValidCurrency(Text, true))
                            {
                                BackColor = Color.Red;
                                errorMsg += " Masukkan penulisan uang dengan benar";
                                QAFieldErrorMsg fem = new QAFieldErrorMsg();
                                //fem.DocId = QAController.DocId;
                                fem.Field = this.LabelText;
                                fem.ErrorMsg = errorMsg;
                                tooltip.Show(string.Empty, this, 0);
                                tooltip.SetToolTip(this, errorMsg);
                                tooltip.Show(errorMsg, this, Width - 40, Height, 2000);
                            }
                        }*/
                    }
                }
            }
            catch (Exception ex)
            {
                // throw ex;
            }
        }

        private void SetBackgroundColor(int index)
        {
            if (!string.IsNullOrEmpty(errorMsg[index]))
                this.Rows[index].DefaultCellStyle.BackColor = Color.Red;
            else
                this.Rows[index].DefaultCellStyle.BackColor = Color.White;
        }

        private void QADataGrid_Validating(object sender, CancelEventArgs e)
        {
            
        }
    }
}
